package com.zhoutao.blog.seven.service.impl;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.zhoutao.blog.seven.dao.model.CommentDao;
import com.zhoutao.blog.seven.dao.repository.ArticleRepository;
import com.zhoutao.blog.seven.dao.repository.CommonRepository;
import com.zhoutao.blog.seven.model.Ref;
import com.zhoutao.blog.seven.model.converter.CommentConverter;
import com.zhoutao.blog.seven.model.enums.RefType;
import com.zhoutao.blog.seven.model.response.Comment;
import com.zhoutao.blog.seven.service.ArticleService;
import com.zhoutao.blog.seven.service.CommonService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@Service
@RequiredArgsConstructor
public class CommonServiceImpl implements CommonService {

    private final CommonRepository commonRepository;

    public final CommentConverter commentConverter;

    private final ArticleRepository articleRepository;

    @Override
    public List<Comment> findByBlogId(Long blogId) {

        Ref<Long> ref = Ref.of(blogId, RefType.ARTICLE);
        final List<CommentDao> commentDaoList = commonRepository.findByRef(ref);
        if (CollectionUtils.isEmpty(commentDaoList)) {
            return Collections.emptyList();
        }

        final List<Comment> comments = commentDaoList.stream().map(commentConverter::converterFrom).collect(Collectors.toList());
        Map<Long, Comment> commentGroup = Maps.newLinkedHashMap();
        for (Comment comment : comments) {
            final Long parentId = comment.getParentId();
            // 说明是第一层评论
            if (parentId == 0 || !commentGroup.containsKey(parentId)) {
                commentGroup.put(comment.getId(), comment);
                continue;
            }

            final Comment entry = commentGroup.get(parentId);
            if (entry == null) {
                continue;
            }
            entry.addSubComment(comment);
        }


        return Lists.newArrayList(commentGroup.values());
    }


    /**
     * 保存文章评论
     */
    public void save(Comment comment) {
        final CommentDao commentDao = commentConverter.converterTO(comment);
        commentDao.setRefType(RefType.ARTICLE.name());
        this.commonRepository.save(commentDao);

        // 文章评论数 + 1
        articleRepository.updateCommentCount(comment.getRefId());
    }
}
